package me.sdevil507.supports.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 原生AES工具类
 * @author heqinzhu
 *
 */

public class AESUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(AESUtil.class);

    //==========号卡认证新增==============

    public static final String DEFAULT_PASSWORD = "abcQWE123$_";

    private static final String DEFAULT_ENCODING = "utf-8";

    private static final String PASSWORD_SALT = "fzCE";

    public static String decrypt(String dataPassword, String encrypted) {
        try {

            byte[] byteMi = Base64.getDecoder().decode(encrypted);
            SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(DEFAULT_ENCODING), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()]));
            byte[] decryptedData = cipher.doFinal(byteMi);
            return new String(decryptedData, DEFAULT_ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encrypt(String dataPassword, String cleartext) {
        try {
            SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(DEFAULT_ENCODING), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()]));
            byte[] encryptedData = cipher.doFinal(cleartext.getBytes(DEFAULT_ENCODING));
            return Base64.getEncoder().encodeToString(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encryptPassword(String dataPassword) {
        try {
            return DigestUtils.md5Hex(String.format("%s%s", dataPassword, PASSWORD_SALT)).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES加密，用于登录时的手机号、邮箱加密
     * @param content 待加密内容
     * @return
     */
    public static String encryptLogin(String content) {
        if (StringUtils.isEmpty(content)) {
            LOGGER.info("AES decrypt: the content is null!");
            return null;
        }
        //判断秘钥是否为16位
        if (!StringUtils.isEmpty(aesKey) && aesKey.length() == 16) {
            try {
                //对密码进行编码
                byte[] bytes = aesKey.getBytes(DEFAULT_ENCODING);
                //设置加密算法，生成秘钥
                SecretKeySpec skeySpec = new SecretKeySpec(bytes, "AES");
                // "算法/模式/补码方式"
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                //选择加密
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
                //根据待加密内容生成字节数组
                byte[] encrypted = cipher.doFinal(content.getBytes(DEFAULT_ENCODING));
                //返回base64字符串
                return Base64Utils.encodeToString(encrypted);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            LOGGER.info("AES decrypt: the aesKey is null or error!");
            return null;
        }

    }

    public static String decryptLogin(String content){
        if(StringUtils.isEmpty(content)){
            LOGGER.info("AES decrypt: the content is null!");
            return null;
        }
        //判断秘钥是否为16位
        if(!StringUtils.isEmpty(aesKey) && aesKey.length() == 16){
            try {
                //对密码进行编码
                byte[] bytes = aesKey.getBytes(DEFAULT_ENCODING);
                //设置解密算法，生成秘钥
                SecretKeySpec skeySpec = new SecretKeySpec(bytes, "AES");
                // "算法/模式/补码方式"
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                //选择解密
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);

                //先进行Base64解码
                byte[] decodeBase64 = Base64Utils.decodeFromString(content);

                //根据待解密内容进行解密
                byte[] decrypted = cipher.doFinal(decodeBase64);
                //将字节数组转成字符串
                return new String(decrypted, DEFAULT_ENCODING);
            } catch (Exception e) {
                LOGGER.info("AES decrypt exception:" + e.getMessage());
                throw new RuntimeException(e);
            }

        }else {
            LOGGER.info("AES decrypt: the aesKey is null or error!");
            return null;
        }
    }

    //==========统一认证==============
    /**
     * 将byte[]转为各种进制的字符串
     * @param bytes byte[]
     * @param radix 可以转换进制的范围，从Character.MIN_RADIX到Character.MAX_RADIX，超出范围后变为10进制
     * @return 转换后的字符串
     */
    public static String binary(byte[] bytes, int radix){
        return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
    }

    /**
     * base 64 encode
     * @param bytes 待编码的byte[]
     * @return 编码后的base 64 code
     */
    public static String base64Encode(byte[] bytes){
        return org.apache.tomcat.util.codec.binary.Base64.encodeBase64String(bytes);
    }

    /**
     * base 64 decode
     * @param base64Code 待解码的base 64 code
     * @return 解码后的byte[]
     * @throws Exception
     */
    public static byte[] base64Decode(String base64Code) throws Exception{
        return StringUtils.isEmpty(base64Code) ? null : org.apache.tomcat.util.codec.binary.Base64.decodeBase64(base64Code);
    }

    /**
     * AES加密
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgenInit(kgen, encryptKey.getBytes());

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));

        return cipher.doFinal(content.getBytes("utf-8"));
    }

    public static byte[] aesEncryptToBytes(String content, byte[] encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgenInit(kgen, encryptKey);

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));

        return cipher.doFinal(content.getBytes("utf-8"));
    }

    /**
     * AES加密为base 64 code
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    public static String aesEncrypt(String content, byte[] encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    /**
     * AES解密
     * @param encryptBytes 待解密的byte[]
     * @param decryptKey 解密密钥
     * @return 解密后的String
     * @throws Exception
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgenInit(kgen, decryptKey.getBytes());

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);

        return new String(decryptBytes,"utf-8");
    }

    public static String aesDecryptByBytes(byte[] encryptBytes, byte[] decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgenInit(kgen, decryptKey);

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);

        return new String(decryptBytes,"utf-8");
    }

    /**
     * 将base 64 code AES解密
     * @param encryptStr 待解密的base 64 code
     * @param decryptKey 解密密钥
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    public static String aesDecrypt(String encryptStr, byte[] decryptKey) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    public static byte[] getAESKey(String encodingAESKey){
        byte[] array = org.apache.tomcat.util.codec.binary.Base64.decodeBase64(encodingAESKey+"=");
        return array;
    }

    /**防止在linux下随机生成key
     * @throws NoSuchAlgorithmException */
    public static void kgenInit(KeyGenerator kgen, byte[] bytes)
            throws NoSuchAlgorithmException{
        //1.防止linux下 随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(bytes);
        //2.根据密钥初始化密钥生成器
        kgen.init(128, secureRandom);
    }

	private static byte[] Decrypt(byte[] text, byte[] key) throws Exception {
		SecretKeySpec aesKey = new SecretKeySpec(key, "AES");

		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, aesKey);
		return cipher.doFinal(text);
	}
	/**
	 * 解密手机号专用 aes方法
	 * @param password
	 * @param key
	 * @return
	 * @throws Exception
	 */
//    public static String DeCodeMobileAES(String password, String key) throws Exception{
//		byte[] keybBytes = MD5STo16Byte.encrypt2MD5toByte16(key);
//		byte[] debase64Bytes = org.apache.tomcat.util.codec.binary.Base64.decodeBase64(password);
//		return new String(Decrypt(debase64Bytes, keybBytes));
//	}

    private static String aesKey =  "CMRI@TK_TK*#2024";

    public static void main(String[] args) {
        String en = AESUtil.encryptLogin("18810668878");
//        String en = AESUtil.encryptLogin("15850782821");
        System.out.println(en);
        String de = AESUtil.decryptLogin(en);
        System.out.println(de);

        String pwd="abcQWE123$_";
        String salt = "fzCE";
        String pwdEn = DigestUtils.md5Hex(String.format("%s%s", pwd, salt)).toUpperCase();
        System.out.println(pwdEn);


        String hashAlgorithmName = "MD5";
        Object credentials = "abcQWE123$_fzCE";
        Object saltT = "";
        int hashIterations = 1;
        Object result = new SimpleHash(hashAlgorithmName,credentials,saltT,hashIterations);
        System.out.println(result);
    }
}
